
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.PUB;
using Apps.Models.PUB;
using Apps.IBLL.PUB;
namespace Apps.BLL.PUB
{
	public partial class PUB_CAR_BLACKLISTBLL: Virtual_PUB_CAR_BLACKLISTBLL,IPUB_CAR_BLACKLISTBLL
	{
        

	}
	public class Virtual_PUB_CAR_BLACKLISTBLL
	{
        [Dependency]
        public IPUB_CAR_BLACKLISTRepository m_Rep { get; set; }

		public virtual List<PUB_CAR_BLACKLISTModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<PUB_CAR_BLACKLIST> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
								a=>a.CAR_ID.Contains(queryStr)
								
								|| a.UPDATE_USER_ID.Contains(queryStr)
								
								|| a.REASON.Contains(queryStr)
								);
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }
		 
		public virtual List<PUB_CAR_BLACKLISTModel> GetPagerList(ref GridPager pager, Expression<Func<PUB_CAR_BLACKLIST, bool>> whereLambda )
        {

            IQueryable<PUB_CAR_BLACKLIST> queryData = m_Rep.GetList(whereLambda); 
             
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

		public virtual List<PUB_CAR_BLACKLISTModel> GetList(Expression<Func<PUB_CAR_BLACKLIST, bool>> whereLambda )
        {

            IQueryable<PUB_CAR_BLACKLIST> queryData = m_Rep.GetList(whereLambda); 
                
            return CreateModelList(ref queryData);
        }

		public virtual List<PUB_CAR_BLACKLISTModel> GetListByParentId(ref GridPager pager, string queryStr,object parentId)
        {
			return new List<PUB_CAR_BLACKLISTModel>();
		}

        public virtual List<PUB_CAR_BLACKLISTModel> CreateModelList(ref IQueryable<PUB_CAR_BLACKLIST> queryData)
        {

            List<PUB_CAR_BLACKLISTModel> modelList = (from r in queryData
                                              select new PUB_CAR_BLACKLISTModel
                                              {
													CAR_ID = r.CAR_ID,
													STATUS = r.STATUS,
													UPDATE_USER_ID = r.UPDATE_USER_ID,
													UPDATE_TIME = r.UPDATE_TIME,
													REASON = r.REASON,
                                                    LPR = r.PUB_CAR.LPR
                                              }).ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, PUB_CAR_BLACKLISTModel model)
        {
            try
            {
                PUB_CAR_BLACKLIST entity = m_Rep.GetById(model.CAR_ID,model.UPDATE_TIME);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new PUB_CAR_BLACKLIST();
               				entity.CAR_ID = model.CAR_ID;
				entity.STATUS = model.STATUS;
				entity.UPDATE_USER_ID = model.UPDATE_USER_ID;
				entity.UPDATE_TIME = model.UPDATE_TIME;
				entity.REASON = model.REASON;
  

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
		 public virtual bool Deletes(ref ValidationErrors errors,Expression<Func<PUB_CAR_BLACKLIST, bool>> whereLambda)
         {
		        try
				{
					using (DBContainer db = new DBContainer())
					{
				
							foreach (var entity in db.PUB_CAR_BLACKLIST.Where(whereLambda))
							{
								db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
							}

							if(db.SaveChanges()>0)
							{
								return true;
							}
							else
							{
								return false;
							}
			
					}
				}
				catch (Exception ex)
				{
					errors.Add(ex.Message);
					ExceptionHander.WriteException(ex);
					return false;
				}
        }

         public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }




        public virtual bool Edit(ref ValidationErrors errors, PUB_CAR_BLACKLISTModel model)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    using (var scope = db.Database.BeginTransaction())
                    {
                        try
                        {
                            PUB_CAR_BLACKLIST entity = m_Rep.GetById(model.CAR_ID, model.UPDATE_TIME);
                            if (entity == null)
                            {
                                errors.Add(Resource.Disable);
                                return false;
                            }
                            bool before = entity.STATUS;
                            entity = new PUB_CAR_BLACKLIST();
                            entity.CAR_ID = model.CAR_ID;
                            entity.STATUS = model.STATUS;
                            entity.UPDATE_USER_ID = model.UPDATE_USER_ID;
                            entity.UPDATE_TIME = DateTime.Now;
                            entity.REASON = model.REASON;

                            m_Rep.Create(entity);
                            if (before != model.STATUS)
                            {
                                string sql = string.Format("update pub_car set status={0} where car_id='{1}'", Convert.ToInt32(model.STATUS), model.CAR_ID);

                                db.Database.ExecuteSqlCommand(sql);
                            }
                            scope.Commit();//正常完成就可以提交
                            return true;
                        }
                        catch (Exception ex)
                        {
                            errors.Add(ex.Message);
                            ExceptionHander.WriteException(ex);
                            scope.Rollback();//发生异常就回滚
                            return false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }






        public virtual PUB_CAR_BLACKLISTModel GetById(object id)
        {
            //if (IsExists(para))
            //{
                PUB_CAR_BLACKLIST entity = m_Rep.GetList(p=>p.CAR_ID==id.ToString()).OrderByDescending(a=>a.UPDATE_TIME).First();
                PUB_CAR_BLACKLISTModel model = new PUB_CAR_BLACKLISTModel();
                model.CAR_ID = entity.CAR_ID;
				model.STATUS = entity.STATUS;
				model.UPDATE_USER_ID = entity.UPDATE_USER_ID;
				model.UPDATE_TIME = entity.UPDATE_TIME;
				model.REASON = entity.REASON;
 
                return model;
            //}
            //else
            //{
            //    return null;
            //}
        }

		public virtual PUB_CAR_BLACKLISTModel GetItem(Expression<Func<PUB_CAR_BLACKLIST, bool>> whereLambda)
        {
 
                PUB_CAR_BLACKLIST entity = m_Rep.GetItem(whereLambda);
                if (entity == null) return null;

                PUB_CAR_BLACKLISTModel model = new PUB_CAR_BLACKLISTModel();
                              				model.CAR_ID = entity.CAR_ID;
				model.STATUS = entity.STATUS;
				model.UPDATE_USER_ID = entity.UPDATE_USER_ID;
				model.UPDATE_TIME = entity.UPDATE_TIME;
				model.REASON = entity.REASON;
 
                return model; 
        }


		 /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<PUB_CAR_BLACKLISTModel> list,ref ValidationErrors errors )
        {
          
            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
			 				 excelFile.AddMapping<PUB_CAR_BLACKLISTModel>(x => x.CAR_ID, "CAR_ID");
				 excelFile.AddMapping<PUB_CAR_BLACKLISTModel>(x => x.STATUS, "STATUS");
				 excelFile.AddMapping<PUB_CAR_BLACKLISTModel>(x => x.UPDATE_USER_ID, "UPDATE_USER_ID");
				 excelFile.AddMapping<PUB_CAR_BLACKLISTModel>(x => x.UPDATE_TIME, "UPDATE_TIME");
				 excelFile.AddMapping<PUB_CAR_BLACKLISTModel>(x => x.REASON, "REASON");
 
            //SheetName
            var excelContent = excelFile.Worksheet<PUB_CAR_BLACKLISTModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new PUB_CAR_BLACKLISTModel();
						 				  entity.CAR_ID = row.CAR_ID;
				  entity.STATUS = row.STATUS;
				  entity.UPDATE_USER_ID = row.UPDATE_USER_ID;
				  entity.UPDATE_TIME = row.UPDATE_TIME;
				  entity.REASON = row.REASON;
 
                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<PUB_CAR_BLACKLISTModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        PUB_CAR_BLACKLIST entity = new PUB_CAR_BLACKLIST();
                       						entity.CAR_ID = model.CAR_ID;
						entity.STATUS = model.STATUS;
						entity.UPDATE_USER_ID = model.UPDATE_USER_ID;
						entity.UPDATE_TIME = model.UPDATE_TIME;
						entity.REASON = model.REASON;
 
                        db.PUB_CAR_BLACKLIST.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
		  public void Dispose()
        { 
            
        }

	}
}
